package cloud.zhixinglu.www.spring.boot.druid.configure;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Servlet;
import java.util.HashMap;

/**
 * <p>
 * DruidConfig
 * </p>
 *
 * @author weixin
 * @date 2023/8/23 18:52
 */
@Slf4j
@Configuration
public class DruidConfig {

    /**
     * 将自定义的 Druid数据源添加到容器中，不再让 Spring Boot 自动创建
     *       绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
     *       @ConfigurationProperties(prefix = "spring.datasource")：作用就是将 全局配置文件中
     *       前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
     * 第一次使用，页面会出现(*) property for user to setup，是因为项目中没有请求过数据库，请求一次就不需要括号中的东西了
     * @return
     */
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    @Bean(destroyMethod = "close", initMethod = "init")
    public DruidDataSource druid() {
        return new DruidDataSource();
    }

    /**
     * 配置druid管理页面的访问控制
     * 访问网址: http://127.0.0.1:7070/druid
     * @return
     */
    @Bean
    public ServletRegistrationBean<Servlet> druidServlet() {
        log.info("init Druid Servlet Configuration");
        ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<>();
        //配置一个拦截器
        servletRegistrationBean.setServlet(new StatViewServlet());
        // 指定拦截器只拦截druid管理页面的请求
        servletRegistrationBean.addUrlMappings("/druid/*");
        HashMap<String, String> initParam = new HashMap<>(4);
        //登录druid管理页面的用户名
        initParam.put("loginUsername", "admin");
        //登录druid管理页面的密码
        initParam.put("loginPassword", "admin");
        //是否允许重置druid的统计信息
        initParam.put("resetEnable", "true");
        //ip白名单，如果没有设置或为空，则表示允许所有访问
        initParam.put("allow", "");
        servletRegistrationBean.setInitParameters(initParam);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean<WebStatFilter> filterRegistrationBean() {
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}
